import { Base64 } from 'js-base64';
import { observable, action, toJS } from 'mobx';
import { Bubble, Toast, Tools } from 'weaver-mobile';
import { ListView } from 'weaver-mobile';
import { ListViewPage, Browser } from 'weaver-mobile-page';
import StaticViewStore from './StaticView';
import API from '../../apis/view';
const getLabel = Tools.getLabel;

const initState = {
  right: 1,
  baseInfo: {},
  defaultBaseInfo: {},
  showAll: false, // 默认显示精简信息
  content: '',
  buttons: [],
  readTopList: [], // 邮件查看情况
  secId: 0,
  crmSecId: 0,
  newParams: {},
  iframeLoading: false,
  iframContent: false,
  iframContentLoading: true,
  mailUserSetting: {},
  secrecyRight: 1, // 密级查看权限
};

//查看邮件页面 store
export default class ViewStore {
  path;
  currentModal;
  @observable readedList;
  @observable unReadList;
  @observable allReadList;
  @observable cusBrowser;
	@observable docBrowser;
	@observable outerFromList = new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2 });
  @observable outerAllReadList = new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2 });
  @observable outerReadedList = new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2 });
  @observable outerunReadList = new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2 });
  @observable params = {}; // 从非List进入View页面取的params
  @observable rightLoading = false;
  @observable baseLoading = false;
  @observable right = initState.right;
  @observable baseInfo = initState.baseInfo;
  @observable defaultBaseInfo = initState.defaultBaseInfo;
  @observable showAll = initState.showAll;
  @observable content = initState.content;
  @observable buttons = initState.buttons;
  @observable secId = initState.secId;
  @observable crmSecId = initState.crmSecId;
  @observable readTopList = initState.readTopList;
  @observable newParams = initState.newParams;
  @observable iframeLoading = initState.iframeLoading;
  @observable iframContent = initState.iframContent;
  @observable iframContentLoading = initState.iframContentLoading;
  @observable staticViewStore = new StaticViewStore();
  @observable receiptMsgVisible = false; // 回执信息显隐
  @observable hasReceipt = false;  // 是否操作了回执
  @observable mailUserSetting = initState.mailUserSetting;
  @observable secrecyRight = initState.secrecyRight;

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    return this;
  }

  @action
  clear = () => this.setState(initState)

	//初始化查看信息
  @action
  doInit = (path, mailId, params) => {
    this.path = path;
    if (params) {
      this.params = { ...this.params, ...params };
    }
    if (mailId) {
      this.params = { ...this.params, mailId };
		}
    this.getRight(this.params);
    this.readedList = new ListViewPage.Store({ route: path, id: 'readList' });
    this.unReadList = new ListViewPage.Store({ route: path, id: 'readList' });
    this.allReadList = new ListViewPage.Store({ route: path, id: 'readList' });
    this.cusBrowser = new Browser.Store({ route: path, id: 'cus' });
    this.docBrowser = new Browser.Store({ route: path, id: 'doc' });
  }

  // 阅读状态初始化
  @action
  doReadInit = (params) => {
    this.getReadCount(params);
    this.getReadList(params);
    this.getReadList({...params, readed: 0 });
    this.getReadList({...params, readed: 1 });
  }

	//初始化外部邮件，发件人和所有收件人查看页面信息
  @action
  doOuterReadInit = () => {
    const { fromSpan = {}, toSpan = { list: [] }, ccSpan = { list: [] }, bccSpan = { list: [] } } = toJS(this.baseInfo);
		this.readTopList = [];
		
		if(fromSpan) {
			this.readTopList.push({
        label: getLabel(2034, '发件人'),
        count: 1,
        key: 'sendfrom'
			});
			let fromSpanList = [];
			fromSpanList.push(fromSpan);
      this.outerFromList = this.outerFromList.cloneWithRows(fromSpanList);
		}
    if (toSpan.list.length > 0) {
      this.readTopList.push({
        label: getLabel(2046, '收件人'),
        count: toSpan.list.length,
        key: 'sendto'
      });
      this.outerAllReadList = this.outerAllReadList.cloneWithRows(toSpan.list);
    }
    if (ccSpan.list.length > 0) {
      this.readTopList.push({
        label: getLabel(17051, '抄送人'),
        count: ccSpan.list.length,
        key: 'sendcc'
      });
      this.outerReadedList = this.outerReadedList.cloneWithRows(ccSpan.list);
    }
    if (bccSpan.list.length > 0) {
      this.readTopList.push({
        label: getLabel(81316, '密送人'),
        count: bccSpan.list.length,
        key: 'sendbcc'
      });
      this.outerunReadList = this.outerunReadList.cloneWithRows(bccSpan.list);
    }
  }

	// 校验是否有权限查看邮件，有权限才加载相关信息，否则提示无权限查看
  @action
  getRight = (params) => {
    this.rightLoading = true;
    API.getRight(params).then(res => {
      this.right = res.viewRight;
      this.secrecyRight = res.classificationRight;
      if (res.viewRight === 1 && res.classificationRight === 1) {
        this.getBase(params);
        this.getDropDown(params);
        this.getContent(params);
        this.getUserMailSetting();
      }
      this.rightLoading = false;
    });
  }

	// 邮件基本信息
  @action
  getBase = (params) => {
    this.baseLoading = true;
    API.getBase(params).then(res => {
      this.defaultBaseInfo = res.defaultBaseInfo;
      this.baseInfo = res.viewBean;
      this.originalMailId = res.viewBean.originalMailId;
      this.receiptMsgVisible = res.viewBean.receiveNeedReceipt;
      this.baseLoading = false;
    });
  }

	// 邮件查看页面，下方操作按钮数据
  @action
  getDropDown = (params) => {
    API.getDropDown(params).then(res => {
      this.buttons = res.viewPageTopDropDown;
    })
  }

	// 一些其他设置信息，如配置页面的导出客户目录，导出文档目录等
  @action 
  getUserMailSetting = () => {
    API.getUserMailSetting().then(res => {
      this.mailUserSetting = res.mailUserSetting;
      this.secId = res.mailUserSetting.secId;
      this.crmSecId = res.mailUserSetting.crmSecId;
    })
  }

	// 获取邮件内容
  @action
  getContent = (params) => {
    this.iframContentLoading = true;
    API.getContent(params).then(res => {
      this.content = Base64.decode(res.mailContent);
      // 情况：1、内容本身为空  2、纯文本内容  3、带有图片的邮件
      this.iframContent = this.content.match(/<img.*?(?:>|\/>)/gi);  // 这封邮件本身就没有图片 返回为null, imgReg.length——>报错
      this.iframContentLoading = false;
    })
  }

  @action
  getReadCount = (params) => {
    API.getReadCount(params).then(res => {
      this.readTopList = res.topList;
    })
  }

  @action
  getReadList = (params) => {
    API.getReadList(params).then(res => {//readed: 空：全部，1：已读，0：未读
      if (params.readed === 1) {
        this.readedList.getData({ dataKey: res.sessionkey });
      } else if (params.readed === 0) {
        this.unReadList.getData({ dataKey: res.sessionkey });
      } else {
        this.allReadList.getData({ dataKey: res.sessionkey });
      }
    })
  }

	// 标星 和 取消标星
  @action
  setStar = (params, callback) => {
    API.setStar(params).then(res => {
      this.updateBaseInfo({ starred: params.star });
      if (callback) callback();
    })
  }

  // 邮件识别发票
  @action
  emailOcrInvoice = (params, callback) => {
    API.emailIdentifyInvoice(params).then(res => {
      if (res.flag) {
        Bubble.success('发票识别成功',4);
      } else {
        Bubble.error('查验失败，发票信息错误', 4);
      }
      this.updateBaseInfo({ emailOcrInvoiceStatus: res.flag?"1":"0" });
      if (callback) callback({ emailOcrInvoiceStatus: res.flag?"1":"0" });
    })
  }

	// 删除邮件
  @action 
  deleteEmail = (params, callback) => {
    API.deleteEmail(params).then(res => {
      if (callback)callback();
    })
  }

  @action
  crmContactRecord = (params) => {
    Toast.loading('Loading...', 1);
    API.crmContactRecord(params).then(res => {
      if (res.status === '1') {
        Bubble.success(getLabel('384412','导出客户联系成功！'));
      } else {
        Bubble.error(getLabel('384413','导出客户联系失败！'));
      }
    })
  }

  @action
  docs = (params) => {
    Toast.loading('Loading...', 1);
    API.docs(params).then(res => {
      if (res.status === '1') {
        Bubble.success(getLabel('384410','导出文档成功！'));
      } else {
        Bubble.error(getLabel('384411','导出文档失败！'));
      }
    })
  }

  @action // 撤回
  recall = (params) => {
    Toast.loading('Loading...', 2); // 接口有点慢 加一下loading
    API.recall(params).then(res => {
      if (res.status === '1'&&res.flag === true) {
        Bubble.success(getLabel(384408, '撤回成功！'));
        const { mailId } = this.params;
        this.updateBaseInfo({ recallstate: 1 });
        this.getDropDown({ mailId });
      } else {
        Bubble.error( getLabel(505893, '撤回失败！您暂无撤回权限，或者可撤回时间已过期，请检查后台邮件撤回相关配置。'));
      }

    });
  }

  @action
  setNewParams = (flag, callback) => {
    const { mailId } = this.params;
    this.newParams = {
      id: mailId,
      flag,
    }
    if (callback) callback();
  }

  @action
  operateUserMailFolder = (params, callback) => {
    API.operateUserMailFolder(params).then(res => {
      if (callback) callback();
    })
  }

  @action // 设为完成
  completeWaitdeal = (params, callback) => {
    API.completeWaitdeal(params).then(res => {
      if (res.status === '1') {
        Bubble.success(getLabel(16746, '设置成功！'))
      }
      this.updateBaseInfo({
        waitdeal: 0,
        waitdealBean: {},
      });
      if (callback && typeof callback === 'function') callback();
    })
  }

  @action
  markEmailToByMobile = (params, star, callback) => {
    API.markEmailToByMobile(params).then(res => {
      this.updateBaseInfo({
        labels: res.labels,
        starred: star,
      });
      if (callback) callback(res);
    })
  }

  @action // 更新baseInfo的值
  updateBaseInfo = (params) => {
    this.baseInfo = {
      ...this.baseInfo,
      ...params,
    }
  }

  @action  // 回执
  getReceiptMsg = (params) => {
    this.hasReceipt = true;
    API.EmailCommonOperation(params).then(res => {
      if (res.flag) {
        params.operateType === 'receiveNeedReceipt' && Bubble.success(getLabel(384416, '回复成功！'));
      } else {
        Bubble.error(res.msg || getLabel(83912, '操作失败！'));
      }
    })
  } 

}
